const REG_PHONE = /^[1][3,4,5,7,8,9][0-9]{9}$/ // 手机号
const REG_VCODE = /^\d{6}$/         // 验证码
const REG_CARDNUMBER = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/ // 身份证号
const REG_CHINESE_NAME = /^[\u4E00-\u9FA5]{2,4}$/ // 中文姓名
const REG_PASSWORD = /^[0-9A-Za-z]{6,20}$/
export function testPassword (v) {
  return REG_PASSWORD.test(v)
}

export function testPhone (v) {
  return REG_PHONE.test(v)
}

export function testVcode (v) {
  return REG_VCODE.test(v)
}

export function testCardNumber (v) {
  return REG_CARDNUMBER.test(v)
}

export function testEmpty (v) {
  return v.trim() === '' || v === null
}

export function testChineseName (v) {
  return REG_CHINESE_NAME.test(v)
}
export function formatDate (date, fmt) {
  let padLeftZero = str => ('00' + str).substr(str.length)
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}
export function getBirthdayFromIdCard (idCard) {
  let birthday = ''
  if (idCard != null && idCard !== '') {
    if (idCard.length === 15) {
      birthday = '19' + idCard.substr(6, 6)
    } else if (idCard.length === 18) {
      birthday = idCard.substr(6, 8)
    }

    birthday = birthday.replace(/(.{4})(.{2})/, '$1-$2-')
  }
  return birthday
}
export function getSexFromIdCard (idCard) {
  let sex = '1'
  if (idCard != null && idCard !== '') {
    if (idCard.length === 15) {
      sex = idCard.substr(14, 1) % 2 === 1 ? '1' : '2'
    } else if (idCard.length === 18) {
      sex = idCard.substr(16, 1) % 2 === 1 ? '1' : '2'
    }
  }
  return sex
}
export function leftTime (time1, time2) {
  let ts = (time1 - time2) / 1000
  let m = Math.floor(ts / 60)
  let s = parseInt(ts % 60)
  return {m, s}
}
export function setLogout () {
  localStorage.removeItem('accessToken')
  localStorage.removeItem('logined')
}
export const HAS_LOGINED = () => localStorage.accessToken !== undefined
